package com.jl15988.chainlog.callback;

import com.jl15988.chainlog.model.ChainApiLog;
import com.jl15988.chainlog.model.ChainMethodLog;
import com.jl15988.chainlog.service.ChainTraceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 跟踪数据收集回调
 * 异步收集监控数据用于可视化
 */
//@Component
@Slf4j
public class TraceCollectorCallback implements ChainApiCallback, ChainMethodCallback {

    @Autowired
    private ChainTraceService chainTraceService;

    @Override
    public void onChainComplete(ChainApiLog chainApiLog, HttpServletRequest request, HttpServletResponse response) {
        try {
            chainTraceService.saveApiLog(chainApiLog);
        } catch (Exception e) {
            log.error("Failed to save API log: {}", chainApiLog.getId(), e);
        }
    }

    @Override
    public void onChainException(ChainApiLog chainApiLog, HttpServletRequest request, HttpServletResponse response, Throwable exception) {
        try {
            chainTraceService.saveApiLog(chainApiLog);
        } catch (Exception e) {
            log.error("Failed to save API log with exception: {}", chainApiLog.getId(), e);
        }
    }

    @Override
    public void onChainComplete(ChainMethodLog chainMethodLog, ChainApiLog chainApiLog, ChainMethodLog parentChainMethodLong) {
        try {
            chainTraceService.saveMethodLog(chainMethodLog);
        } catch (Exception e) {
            log.error("Failed to save method log: {}", chainMethodLog.getId(), e);
        }
    }

    @Override
    public void onChainException(ChainMethodLog chainMethodLog, ChainApiLog chainApiLog, ChainMethodLog parentChainMethodLong, Throwable exception) {
        try {
            chainTraceService.saveMethodLog(chainMethodLog);
        } catch (Exception e) {
            log.error("Failed to save method log with exception: {}", chainMethodLog.getId(), e);
        }
    }
}